package com.hjxy.codetools.controller;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeWapPayModel;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.internal.util.StringUtils;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.hjxy.codetools.interfa.ArtitleServiceInterface;
import com.hjxy.codetools.interfa.PayOrderServiceInterface;
import com.hjxy.codetools.interfa.TuserServiceInterface;
import com.hjxy.codetools.model.ArtitleModel;
import com.hjxy.codetools.model.PayOrderModel;
import com.hjxy.codetools.model.TuserModel;
import com.hjxy.codetools.util.QRCodeUtil;
import com.hjxy.codetools.util.SnowFlake;
import com.hjxy.codetools.util.StrUtil;
import com.hjxy.codetools.util.alipay.AlipayConfig;
import com.hjxy.codetools.util.wxpay.sdk.WXPayConfig;
import com.hjxy.codetools.util.wxpay.sdk.WXPayConstants;
import com.hjxy.codetools.util.wxpay.sdk.WXPayRequest;
import com.hjxy.codetools.util.wxpay.sdk.WXPayUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.sql.Timestamp;
import java.util.*;

@RestController
public class RestPayController {
    @Autowired
    ArtitleServiceInterface artitleServiceInterface;
    @Autowired
    PayOrderServiceInterface payOrderServiceInterface;
    @Autowired
    TuserServiceInterface tuserServiceInterface;
    WXPayConfig wxPayConfig=new WXPayConfig();

    WXPayUtil wxPayUtil=new WXPayUtil();

    /**
     * nativepay
     * 前端 微信pc native 扫码支付接口
     * 返回微信微信支付二维码
     * 用于用户扫描二维码支付
     * 入参为 订单编号
     */
    @PostMapping(value = "/api/pwpay")
    public Map<String, Object> pwpay(HttpServletRequest req, HttpServletResponse response) throws Exception {
        System.out.println("/api/pwpay-");
        Map<String, Object> resultMap = new HashMap<>();
        Map<String,String> parMap=new HashMap<>();
        BufferedReader br = new BufferedReader(new InputStreamReader(req.getInputStream()));
        StringBuffer sb = new StringBuffer();
        String s = null;
        while ((s = br.readLine()) != null) {
            sb.append(s);
        }

        JSONObject reqObject = JSONObject.parseObject(sb.toString());
        if (reqObject.containsKey("orCode")){
            String orCode=reqObject.getString("orCode");
            System.out.println("orCode--"+orCode);
            parMap.put("ordercode",orCode);
            //去查询对应的orCode的价格和是否存在
            List<PayOrderModel> payOrderModels=payOrderServiceInterface.getPayOrderInfo(parMap);
            if (payOrderModels == null || payOrderModels.size()<=0) {
                //不存在该订单号 被篡改了
                resultMap.put("code",50000);
                resultMap.put("data","未查询到该订单号");
                System.out.println("未查询到该订单号");
            }
            else
            {
                //金额是否被篡改
                if (reqObject.containsKey("paynum")){

                    if(reqObject.getIntValue("paynum")!=payOrderModels.get(0).getPaynum()){
                        //金额被篡改
                    }
                    else
                    {
                        parMap.clear();

                        parMap.put("appid",wxPayConfig.getAppID());
                        parMap.put("mch_id",wxPayConfig.getMchID());
                        parMap.put("nonce_str",WXPayUtil.generateNonceStr());
                        parMap.put("body","支付");
                        parMap.put("out_trade_no",orCode);
                        parMap.put("total_fee",String.valueOf(reqObject.getIntValue("paynum")*100));
                        //  parMap.put("total_fee","1");
                        parMap.put("spbill_create_ip","xxx");//服务器ip地址
                        parMap.put("notify_url","http://xxx/api/pwnotifyPay");
                        parMap.put("trade_type","NATIVE");
                        String keyStr=wxPayConfig.getMchKey();//商户密钥
                        String SignStr=WXPayUtil.generateSignature(parMap,wxPayConfig.getMchKey());
                        parMap.put("sign",SignStr);
                        String postXml=WXPayUtil.mapToXml(parMap);
                        System.out.println("postXml--"+postXml);
                        WXPayRequest wxPayRequest=new WXPayRequest(wxPayConfig);
                        String resultXml=  wxPayRequest.requestOnce(WXPayConstants.DOMAIN_API, WXPayConstants.UNIFIEDORDER_URL_SUFFIX,WXPayUtil.generateNonceStr(),postXml,5000,5000,false);
                        System.out.println("resultXml--"+resultXml);
                        Map<String,String> resultxmlMap=WXPayUtil.xmlToMap(resultXml);

                        if (resultxmlMap.containsKey("return_code")){
                            System.out.println(resultxmlMap.get("return_code"));
                            if ("SUCCESS".equals(resultxmlMap.get("return_code"))){
                                //判断resultcode是否成功
                                if (resultxmlMap.containsKey("result_code")){
                                    if ("SUCCESS".equals(resultxmlMap.get("result_code"))){
                                        //此时才会返回 支付的二维码链接
                                        String code_url=resultxmlMap.get("code_url");
                                        System.out.println("code_url--"+code_url);
                                        //生成二维码
                                        ServletOutputStream sos =  response.getOutputStream();
                                        String base = QRCodeUtil.encodeByBase(code_url, sos);//调用生成二维码的方法
                                        sos.flush();
                                        resultMap.put("code",20000);
                                        resultMap.put("data",base);
                                    }
                                    else
                                    {
                                        resultMap.put("code",50000);
                                        resultMap.put("data","业务结果错误，具体请查看日志记录");
                                    }
                                }
                            }
                            else
                            {
                                //统一下单接口返回错误 将错误信息记录到日志中
                                resultMap.put("code",50000);
                                resultMap.put("data","状态码结果错误，具体请查看日志记录");
                            }
                        }
                    }
                }
            }
        }
        return resultMap;
    }


    /**
     * pc native 支付成功后
     * 微信异步回调函数
     * @return
     */
    @PostMapping(value = "/api/pwnotifyPay")
    public String pwnotifyPay(HttpServletRequest req, HttpServletResponse response) throws Exception{
        System.out.println("回调");
        BufferedReader br = new BufferedReader(new InputStreamReader(req.getInputStream()));
        StringBuffer sb = new StringBuffer();
        String s = null;
        while ((s = br.readLine()) != null) {
            sb.append(s);
        }
        br.close();

        Map<String,String> resultxmlMap=WXPayUtil.xmlToMap(sb.toString());
        System.out.println("resultxmlMap--"+resultxmlMap);
        if (resultxmlMap.containsKey("return_code")){

            if ("SUCCESS".equals(resultxmlMap.get("return_code"))){
                //判断resultcode是否成功
                if (resultxmlMap.containsKey("result_code")){

                    if ("SUCCESS".equals(resultxmlMap.get("result_code"))){
                        //此时才是最终成功结果
                        //更新订单业务逻辑 此时返回的具体参数 需要测试环境下具体查看
                        String out_trade_no=resultxmlMap.get("out_trade_no");

                        Map<String,String> parMap=new HashMap<>();
                        parMap.put("ordercode",out_trade_no);
                        parMap.put("paytype","0");//微信支付
                        parMap.put("payresult","1");
                        payOrderServiceInterface.upPayOrder(parMap);


                        //插入新用户
                        SnowFlake snowFlake=new SnowFlake(0,0);
                        TuserModel tuserModel = new TuserModel();
                        tuserModel.setTname(StrUtil.getStringRandom(4));
//                        tuserModel.setPass(String.valueOf(snowFlake.nextId()));
                        tuserModel.setPass(StrUtil.getStringRandom(4));
                        tuserModel.setOrcode(out_trade_no);
                        tuserServiceInterface.insertTuser(tuserModel);



                        //回复微信 接受成功
                        System.out.println("回复微信 接受成功");
                        String content = "<xml>" + "<return_code><![CDATA[SUCCESS]]></return_code>" + "<return_msg>OK</return_msg>"
                                + "</xml>";
                        PrintStream out = new PrintStream(response.getOutputStream());
                        out.print(content);
                        out.flush();

                    }
                    else
                    {
                        System.out.println("result_code不为真--");
                    }
                }
            }
            else
            {

            }
        }
        return null;
    }

    /**
     * 微信手机端支付
     * 先要获取到openid
     * @param request
     * @param response
     * @return
     * @throws Exception
     */

    @PostMapping(value = "/api/getopenid")
    public Map<String,Object> getopenid(HttpServletRequest request, HttpServletResponse response) throws Exception {
         System.out.println("getopenid");
        Map<String,Object> resultMap=new HashMap<>();
        Map<String,String> parMap=new HashMap<>();
        BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream()));
        StringBuffer sb = new StringBuffer();
        String s = null;
        while ((s = br.readLine()) != null) {
            sb.append(s);
        }
        JSONObject reqObject = JSONObject.parseObject(sb.toString());
        if (reqObject.containsKey("orCode")){
            String orCode=reqObject.getString("orCode");
            System.out.println("orCode--"+orCode);
            parMap.put("ordercode",orCode);
                //去查询对应的orCode的价格和是否存在
                List<PayOrderModel> payOrderModels=payOrderServiceInterface.getPayOrderInfo(parMap);
                if (payOrderModels == null || payOrderModels.size()<=0) {
                    //不存在该订单号 被篡改了
                    resultMap.put("code",50000);
                    resultMap.put("data","未查询到该订单号");
                    System.out.println("未查询到该订单号");
                }
                else
                {
                    if (reqObject.containsKey("paynum")){
                        if(reqObject.getIntValue("paynum")!=payOrderModels.get(0).getPaynum()){
                            //金额被篡改
                        }
                        else {
                            String redirectUrl= URLEncoder.encode("http://xxx/WechatUerInfo?orCode="+orCode,"UTF-8");
                            String uuid= UUID.randomUUID().toString();
                            //拼接 微信授权页面路径地址
                            String url="https://open.weixin.qq.com/connect/oauth2/authorize?appid="+wxPayConfig.getAppID() +
                                    "&redirect_uri="+redirectUrl+"&&response_type=code" +
                                    "&scope=snsapi_userinfo&state="+uuid+"&m=oauth2#wechat_redirect";
                            resultMap.put("code","20000");
                            resultMap.put("data",url);
                        }
                    }
                }
        }
        return resultMap;
    }

    /**
     * 手机端 支付成功后
     * 微信异步回调函数
     * @return
     */
    @PostMapping(value = "/api/mwnotifyPay")
    public String mwnotifyPay(HttpServletRequest req, HttpServletResponse response) throws Exception{
        System.out.println("mwnotifyPay--");
        BufferedReader br = new BufferedReader(new InputStreamReader(req.getInputStream()));
        StringBuffer sb = new StringBuffer();
        String s = null;
        while ((s = br.readLine()) != null) {
            sb.append(s);
        }
        br.close();
        System.out.println("sb--"+sb.toString());
        Map<String,String> resultxmlMap=WXPayUtil.xmlToMap(sb.toString());
        if (resultxmlMap.containsKey("return_code")){

            if ("SUCCESS".equals(resultxmlMap.get("return_code"))){
                //判断resultcode是否成功
                if (resultxmlMap.containsKey("result_code")){

                    if ("SUCCESS".equals(resultxmlMap.get("result_code"))){
                        //此时才是最终成功结果
                        //更新订单业务逻辑 此时返回的具体参数 需要测试环境下具体查看

                        String out_trade_no=resultxmlMap.get("out_trade_no");
                        Map<String,String> parMap=new HashMap<>();
                        parMap.put("ordercode",out_trade_no);
                        parMap.put("paytype","0");//微信支付
                        parMap.put("payresult","1");
                        payOrderServiceInterface.upPayOrder(parMap);
                        System.out.println("SUCCESS--");


                        //插入新用户
                        SnowFlake snowFlake=new SnowFlake(0,0);
                        TuserModel tuserModel = new TuserModel();
                        tuserModel.setTname(StrUtil.getStringRandom(4));
//                        tuserModel.setPass(String.valueOf(snowFlake.nextId()));
                        tuserModel.setPass(StrUtil.getStringRandom(4));
                        tuserModel.setOrcode(out_trade_no);
                        tuserServiceInterface.insertTuser(tuserModel);




                        //回复微信 接受成功
                        String content = "<xml>" + "<return_code><![CDATA[SUCCESS]]></return_code>" + "<return_msg>OK</return_msg>"
                                + "</xml>";
                        PrintStream out = new PrintStream(response.getOutputStream());
                        out.print(content);
                        out.flush();
                    }
                    else
                    {

                    }
                }
            }
            else
            {

            }
        }
        return null;
    }

    /**
     * pc  native
     * 支付宝支付
     * 由于支付宝 native方式 出现二维码比较慢
     * 所以
     * 此处二维码指向的是 利用手机端唤起app的方式
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @PostMapping(value = "/api/paliPay")
    public Map<String,Object> perpcPay(HttpServletRequest request, HttpServletResponse response) throws Exception {
        System.out.println("api/paliPay--");
        Map<String, Object> resultMap = new HashMap<>();
        Map<String,String> parMap=new HashMap<>();
        BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream()));
        StringBuffer sb = new StringBuffer();
        String s = null;
        while ((s = br.readLine()) != null) {
            sb.append(s);
        }
        JSONObject reqObject = JSONObject.parseObject(sb.toString());
        if (reqObject.containsKey("orCode")) {
            String orCode = reqObject.getString("orCode");

            parMap.put("ordercode",orCode);
            //去查询对应的orCode的价格和是否存在
            List<PayOrderModel> payOrderModels=payOrderServiceInterface.getPayOrderInfo(parMap);
            if (payOrderModels == null || payOrderModels.size()<=0) {
                //不存在该订单号 被篡改了
                resultMap.put("code",50000);
                resultMap.put("data","未查询到该订单号");
                System.out.println("未查询到该订单号");
            }
            else
            {
                if (reqObject.containsKey("paynum")){

                    if(reqObject.getIntValue("paynum")!=payOrderModels.get(0).getPaynum()){
                        //金额被篡改
                    }
                    else
                    {
                        String paynum=reqObject.getString("paynum");
                        //生成二维码
                        ServletOutputStream sos =  response.getOutputStream();
                        String base = QRCodeUtil.encodeByBase("http://xxx/api/paliPay/"+orCode, sos);//调用生成二维码的方法
                        sos.flush();
                        resultMap.put("code",20000);
                        resultMap.put("data",base);
                    }
                }
            }
        }
        return resultMap;
    }


    /**
     *  pc端 native支付二维码也是指向的手机端支付方式
     *  故其二维码调用方式也是这个方法
     * @param orCode
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @GetMapping(value = "/api/paliPay/{orCode}")
    public String paliPay(@PathVariable String orCode, HttpServletRequest request, HttpServletResponse response) throws Exception {
        System.out.println("api/pmaliPay--");
        Map<String,String> parMap=new HashMap<>();
        if(!StringUtils.isEmpty(orCode)){
            parMap.put("ordercode",orCode);
            //去查询对应的card的价格 测试时候免除
            List<PayOrderModel> payOrderModels=payOrderServiceInterface.getPayOrderInfo(parMap);
            if (payOrderModels == null || payOrderModels.size()<=0) {
                System.out.println("不存在该订单号 被篡改了 当前单号--"+orCode);
                //不存在该订单号 被篡改了
//                resultMap.put("code","50000");
//                resultMap.put("data","未查询到该订单号");
            }
            else
            {
                // 付款金额，必填
                String total_amount=String.valueOf(payOrderModels.get(0).getPaynum());
                // String total_amount="0.01";
                //自定义参数，可空
                String passback_params = orCode;
                // 商户订单号，商户网站订单系统中唯一订单号，必填
                String out_trade_no =orCode;
                // 商品描述，可空
                String body = "订单支付";
                // 订单名称，必填
                String subject = "订单支付";
                // 超时时间 可空
                String timeout_express="2m";
                // 销售产品码 必填
                String product_code="QUICK_WAP_WAY";
                // SDK 公共请求类，包含公共请求参数，以及封装了签名与验签，开发者无需关注签名与验签
                //调用RSA签名方式
                AlipayClient client = new DefaultAlipayClient(AlipayConfig.URL, AlipayConfig.APP_ID, AlipayConfig.MERCHANT_PRIVATE_KEY, AlipayConfig.FORMAT, AlipayConfig.CHARSET, AlipayConfig.ALIPAY_PUBLIC_KEY,AlipayConfig.SIGN_TYPE);
                AlipayTradeWapPayRequest alipay_request=new AlipayTradeWapPayRequest();
                // 封装请求支付信息
                AlipayTradeWapPayModel model = new AlipayTradeWapPayModel();
                model.setOutTradeNo(out_trade_no);
                model.setSubject(subject);
                model.setTotalAmount(total_amount);
                // model.setTotalAmount(String.valueOf(0.01));
                model.setBody(body);
                model.setTimeoutExpress(timeout_express);
                model.setProductCode(product_code);
                model.setPassbackParams(URLEncoder.encode(passback_params,"UTF-8"));
                alipay_request.setBizModel(model);
                // 设置异步通知地址
                alipay_request.setNotifyUrl("http://xxx/api/pmalipay/pmalipay_notify");
                // 设置同步地址
                alipay_request.setReturnUrl("http://xxx/mpaycg/"+orCode);
                // form表单生产
                String form = "";
                try {
                    // 调用SDK生成表单
                    form = client.pageExecute(alipay_request).getBody();
                    System.out.println(" pmaliPay form--"+form);
                    response.setContentType("text/html;charset=" + AlipayConfig.CHARSET);
                    response.getWriter().write(form);//直接将完整的表单html输出到页面
                    response.getWriter().flush();
                    response.getWriter().close();
                } catch (AlipayApiException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
        return null;
    }


    /**
     * 支付宝h5支付
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @PostMapping(value = "/api/pmaliPay")
    public String pmaliPay(@RequestParam("orCode") String orCode,@RequestParam("paynum") String paynum,HttpServletRequest request, HttpServletResponse response) throws Exception {
        System.out.println("api/pmaliPay--");
        Map<String,String> parMap=new HashMap<>();

            parMap.put("ordercode",orCode);
            //去查询对应的orCode的价格和是否存在
            List<PayOrderModel> payOrderModels=payOrderServiceInterface.getPayOrderInfo(parMap);
            if (payOrderModels == null || payOrderModels.size()<=0) {
                //不存在该订单号 被篡改了
//                resultMap.put("code",50000);
//                resultMap.put("data","未查询到该订单号");
                System.out.println("未查询到该订单号");
            }
            else {

                    if (Integer.parseInt(paynum) != payOrderModels.get(0).getPaynum()) {
                        //金额被篡改

                    } else {
                                // 付款金额，必填
                                String total_amount=String.valueOf(payOrderModels.get(0).getPaynum());
                        //  String total_amount="0.01";
                                //自定义参数，可空
                                String passback_params = orCode;
                                // 商户订单号，商户网站订单系统中唯一订单号，必填
                                String out_trade_no =orCode;
                                // 商品描述，可空
                                String body = "订单支付";
                                // 订单名称，必填
                                String subject = "订单支付";
                                // 超时时间 可空
                                String timeout_express="2m";
                                // 销售产品码 必填
                                String product_code="QUICK_WAP_WAY";
                                // SDK 公共请求类，包含公共请求参数，以及封装了签名与验签，开发者无需关注签名与验签
                                //调用RSA签名方式
                                AlipayClient client = new DefaultAlipayClient(AlipayConfig.URL, AlipayConfig.APP_ID, AlipayConfig.MERCHANT_PRIVATE_KEY, AlipayConfig.FORMAT, AlipayConfig.CHARSET, AlipayConfig.ALIPAY_PUBLIC_KEY,AlipayConfig.SIGN_TYPE);
                                AlipayTradeWapPayRequest alipay_request=new AlipayTradeWapPayRequest();
                                // 封装请求支付信息
                                AlipayTradeWapPayModel model = new AlipayTradeWapPayModel();
                                model.setOutTradeNo(out_trade_no);
                                model.setSubject(subject);
                                model.setTotalAmount(total_amount);
                             // model.setTotalAmount(String.valueOf(0.01));
                                model.setBody(body);
                                model.setTimeoutExpress(timeout_express);
                                model.setProductCode(product_code);
                                model.setPassbackParams(URLEncoder.encode(passback_params,"UTF-8"));
                                alipay_request.setBizModel(model);
                                // 设置异步通知地址
                                alipay_request.setNotifyUrl("http://xxx/api/pmalipay/pmalipay_notify");
                                // 设置同步地址
                                alipay_request.setReturnUrl("http://xxx/mpaycg/"+orCode);
                                // form表单生产
                                String form = "";
                                try {
                                    // 调用SDK生成表单
                                    form = client.pageExecute(alipay_request).getBody();
                                    System.out.println(" pmaliPay form--"+form);
                                    response.setContentType("text/html;charset=" + AlipayConfig.CHARSET);
                                    response.getWriter().write(form);//直接将完整的表单html输出到页面
                                    response.getWriter().flush();
                                    response.getWriter().close();
                                } catch (AlipayApiException e) {
                                    // TODO Auto-generated catch block
                                    e.printStackTrace();
                                }
                            }

                }

        return null;
    }
    /**
     * 支付宝h5支付
     * 异步回调
     * 由于pc端 native支付二维码也是指向的手机端支付方式
     * 故而其回调函数也是这个方法
     * @param request
     * @return
     * @throws IOException
     */
    @PostMapping(value = "api/pmalipay/pmalipay_notify")
    public String pmalipay_notify(HttpServletRequest request,HttpServletResponse response) throws Exception {
        System.out.println(" pmalipay_notify--");
        Map<String, String> reqObject = convertRequestParamsToMap(request);
        String out_trade_no=reqObject.get("out_trade_no");
        String trade_status= reqObject.get("trade_status");
        System.out.println(" trade_status--"+trade_status);
        try {
            boolean signVerified = AlipaySignature.rsaCheckV1(reqObject, AlipayConfig.ALIPAY_PUBLIC_KEY, AlipayConfig.CHARSET, AlipayConfig.SIGN_TYPE);
            //无论同步异步都要验证签名
            if(signVerified){
                if(trade_status.equals("TRADE_FINISHED") || trade_status.equals("TRADE_SUCCESS")){
                    //处理自己系统的业务逻辑，如：将支付记录状态改为成功，需要返回一个字符串success告知支付宝服务器

                    //更新订单业务逻辑 此时返回的具体参数 需要测试环境下具体查看

                    Map<String,String> parMap=new HashMap<>();
                    //为了防止 支付宝方反复调用该回调方法出现问题 新增订单状态是否更新查询操作
                    parMap.clear();
                    parMap.put("ordercode",out_trade_no);
                    parMap.put("payresult","1");
                    List<PayOrderModel> tmppayOrderModels=payOrderServiceInterface.getPayOrderInfo(parMap);
                    if (tmppayOrderModels!=null&&tmppayOrderModels.size()>0) {
                        //说明该订单已经支付完成 此次进入该行数 非第一次回调 后面的逻辑无需处理
                        return "success";
                    }
                    else
                    {
                        parMap.clear();
                        parMap.put("ordercode",out_trade_no);
                        parMap.put("paytype","1");//支付宝支付
                        parMap.put("payresult","1");
                        payOrderServiceInterface.upPayOrder(parMap);
                        System.out.println(" success--");



                        //插入新用户
                        SnowFlake snowFlake=new SnowFlake(0,0);
                        TuserModel tuserModel = new TuserModel();
                        tuserModel.setTname(StrUtil.getStringRandom(4));
                        tuserModel.setPass(StrUtil.getStringRandom(4));
//                        tuserModel.setPass(String.valueOf(snowFlake.nextId()));
                        tuserModel.setOrcode(out_trade_no);
                        tuserServiceInterface.insertTuser(tuserModel);


                        //通知支付宝 支付成功

                        String content = "success";
                        PrintStream out = new PrintStream(response.getOutputStream());
                        out.print(content);
                        out.flush();


                        return "success";
                    }

                } else {
                    //支付失败不处理业务逻辑
                    return "failure";
                }
            }else {
                //签名验证失败不处理业务逻辑
                return "failure";
            }
        } catch (AlipayApiException e) {
            e.printStackTrace();
            return "failure";
        }
    }

    //将请求中的参数转换为Map
    private Map<String, String> convertRequestParamsToMap(HttpServletRequest request) {
        Map<String, String> retMap = new HashMap();
        Set<Map.Entry<String, String[]>> entrySet = request.getParameterMap().entrySet();
        Iterator var3 = entrySet.iterator();

        while(true) {
            while(var3.hasNext()) {
                Map.Entry<String, String[]> entry = (Map.Entry)var3.next();
                String name = (String)entry.getKey();
                String[] values = (String[])entry.getValue();
                int valLen = values.length;
                if(valLen == 1) {
                    retMap.put(name, values[0]);
                } else if(valLen <= 1) {
                    retMap.put(name, "");
                } else {
                    StringBuilder sb = new StringBuilder();
                    String[] var9 = values;
                    int var10 = values.length;

                    for(int var11 = 0; var11 < var10; ++var11) {
                        String val = var9[var11];
                        sb.append(",").append(val);
                    }

                    retMap.put(name, sb.toString().substring(1));
                }
            }

            return retMap;
        }
    }

    //将字符串转换为UTF-8编码以防出现乱码错误
    private String getUTF8XMLString(String xml) {
        StringBuffer sb = new StringBuffer();
        sb.append(xml);
        String xmString = "";
        String xmlUTF8="";
        try {
            xmString = new String(sb.toString().getBytes("UTF-8"));
            xmlUTF8 = URLEncoder.encode(xmString, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return xmlUTF8;
    }

}
